<script setup lang="ts">
import { fabric } from "fabric"; // 引入图片处理图
import { ref, onMounted } from "vue";
const imgRefs: any[] = []; // 图片组
// for (let i=0; i<4; i++) {
//   imgRefs[i] = ref(); // 图片的引用
// }
// const imgRef1 = ref();
// const imgRef2 = ref();
// const imgRef3 = ref();
// const imgRef4 = ref();

// const refs = {
//   1: imgRef1,
//   2: imgRef2,
//   3: imgRef3,
//   4: imgRef4,
// }

let canvas;

onMounted(() => {
  canvas = new fabric.Canvas("canvas", { width: 1500, height: 800 }); // 获取到canvas
  // // 添加文字
  // const text = new fabric.Text('Hello World!'); // 画一个文字
  // canvas.add(text);

  // const img = new fabric.Image(imgRef.value); // 画一个图片
  // canvas.add(img);

  // 设置背景图片
  // canvas.setBackgroundImage({
  //   source: '/box.jpg', // 图片地址
  //   repeat: 'repeat' // 图片重复展示
  // })

  // canvas.setBackgroundImage('/box.jpg', );

  fabric.Image.fromURL("/@assets/img/box.png", function (oImg) {
    // 这里的oImg是一个fabric.Image对象
    // 将其添加到canvas中即可
    // canvas.setBackgroundImage(oImg);
    // canvas.renderAll(); // 更新canvas上的所有对象，包括背景图片
    oImg.scaleX = canvas.width/oImg.width
    oImg.scaleY =canvas.height / oImg.height
  });
});

const addImage = (i: number) => {
  console.log("=================canvas", canvas);
  const img = new fabric.Image(imgRefs[i - 1], {
    top: 20,
    left: 90,
    angle: 20,
  });
  canvas.add(img);
};

const save = () => {
  // 将canvas数据转成base64数据
  const base64 = canvas.toDataURL("image/png");
  const img = base64.replace("image/png", "image/octet-stream"); // 将canvas转换为图片

  const link = document.createElement("a"); // 创建一个新的 a 元素
  link.href = img;
  link.download = "download.png"; // 设置图片名
  link.click(); // 模拟点击事件，开始下载图片
};

const setSefs = (el: any) => {
  // 参数就是dom节点或者子组件的实例
  imgRefs.push(el); // 从0开始
};
</script>

<template>
  <!-- <canvas width="400" height="400" id="canvas"></canvas> -->
  <canvas id="canvas"></canvas>
  <!-- <img ref="imgRef" src="/head.jpg" /> -->
  <img class="img" v-for="i in 4" :key="i" :ref="setSefs" :src="'@/assets/img/'+i+'.png'" @click="addImage(i)" />
  <!-- <img class="img" ref="imgRef1" src="/1.png" @click="addImage(1)" />
  <img class="img" ref="imgRef2" src="/2.png" @click="addImage(2)" />
  <img class="img" ref="imgRef3" src="/3.png" @click="addImage(3)" />
  <img class="img" ref="imgRef4" src="/4.png" @click="addImage(4)" /> -->
  <button @click="save()">导出所有的女友</button>
</template>

<style scoped>
#canvas {
  border: 1px solid #d3d3d3;
  margin: 10px;
}
.img {
  margin: 4px;
  margin-top: 50px;
  width: 40px;
  height: 60px;
  cursor: pointer;
}
</style>